package model

import (
	"context"
	"gorm.io/gorm"
	"strconv"
	"strings"
)

type Goods struct {
	gorm.Model
	GoodsName  string  `gorm:"type:varchar(50)"`
	GoodsPrice float64 `gorm:"type:decimal(10,2)"`
	GoodsNum   int     `gorm:"type:int"`
	Img        string  `gorm:"varchar(100)"`
	Status     int     `gorm:"type:int"`
}

func CreateGoods(goods Goods) Goods {
	g := Goods{}
	db.Where("goods_name", goods.GoodsName).Find(&g)
	if g.ID != 0 {
		goods.ID = g.ID
		db.Save(goods)
		return goods
	}
	db.Create(goods)
	st.Set(context.Background(), "goodsid "+strconv.Itoa(int(g.ID)), g.GoodsNum, 0)
	return goods
}

func DownGoods(goodsid int) string {
	g := Goods{}
	db.Where("id", goodsid).Find(&g)
	if g.ID == 0 {
		return "0"
	}
	g.Status = 0
	db.Save(&g)
	return "1"
}

func List(page int, search string) []Goods {
	goods := []Goods{}
	if page == 0 {
		page = 1
	}
	pageSize := 3
	stt := strings.TrimSpace(search)
	if len(stt) == 0 {
		offset := (page - 1) * pageSize
		db.Offset(offset).Limit(pageSize).Find(&goods)
		return goods
	}
	offset := (page - 1) * pageSize
	db.Where("goods_name LIKE", "%"+stt+"%").Offset(offset).Limit(pageSize).Find(&goods)
	return goods
}
